package com.map;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class GetDirectionbyAudio extends Activity implements OnInitListener {

	EditText start_point;
	EditText end_point;
	ImageButton getAudio_Direction;
	private Runnable getXml;
	private Handler handler;
	private String str_start_point;
	private String str_end_point;
	private int size;
	private String instructions[];
	private String value;
	private TextToSpeech tts;
	private String myLan;
	private String myLong;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.direction_by_audio);

		start_point = (EditText) findViewById(R.id.edit_start_audio);
		end_point = (EditText) findViewById(R.id.edit_end_audio);
		getAudio_Direction = (ImageButton) findViewById(R.id.bt_getdirection_audio);

		myLan = getIntent().getStringExtra("MYLAN");
		myLong = getIntent().getStringExtra("MYLONG");

		tts = new TextToSpeech(this, this);

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (value.equals("OK")) {
					value = "Hello, this is direction for you. There are "
							+ size + "step. Let's go step by step.... "
							+ printString(instructions)
							+ "... Thank you. Goodluck for you! ";
					tts.speak(value, TextToSpeech.QUEUE_FLUSH, null);

				} else {
					value = value + ". " + "please check information";
					tts.speak(value, TextToSpeech.QUEUE_FLUSH, null);
				}

			}

		};

		getXml = new Runnable() {

			public void run() {
				// TODO Auto-generated method stub

				StringBuilder urlString = new StringBuilder();
				urlString
						.append("http://maps.googleapis.com/maps/api/directions/xml?origin=");
				urlString.append(str_start_point);
				urlString.append("&destination=");
				urlString.append(str_end_point);
				urlString.append("&sensor=false");
				urlString.append("&language=en");

				Document doc = null;
				HttpURLConnection urlConnection = null;
				URL url = null;
				DocumentBuilderFactory dbf = null;
				DocumentBuilder db = null;

				try {
					url = new URL(urlString.toString());
					urlConnection = (HttpURLConnection) url.openConnection();
					int res = urlConnection.getResponseCode();
					if (res == HttpURLConnection.HTTP_OK) {
						dbf = DocumentBuilderFactory.newInstance();
						db = dbf.newDocumentBuilder();
						doc = db.parse(urlConnection.getInputStream());
						// xử lí dữ liệu lấy từ google
						Element elementOfDoc = doc.getDocumentElement();

						// lấy nội dung của thẻ <status>
						NodeList nodelist = elementOfDoc
								.getElementsByTagName("status");
						value = nodelist.item(0).getFirstChild().getNodeValue();
						if (value.equals("OK")) {
							NodeList node_Step = elementOfDoc
									.getElementsByTagName("step");
							getDataOfStepNode(node_Step);
						}
					}

				} catch (MalformedURLException e) {
					Log.d("xxxxx", "MalformedURLException:");
					e.printStackTrace();
				} catch (IOException e) {
					Log.d("xxxxx", "IOException:");
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					Log.d("xxxxx", "ParserConfigurationException:");
					e.printStackTrace();
				} catch (SAXException e) {
					Log.d("xxxxx", "SAXException:");
					e.printStackTrace();
				}

				Message msg = handler.obtainMessage();
				handler.sendMessage(msg);
			}
		};

		getAudio_Direction.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				str_start_point = start_point.getText().toString();
				str_end_point = end_point.getText().toString();
				if (str_start_point.equalsIgnoreCase("Từ đây")) {
					str_start_point = myLan + "," + myLong;
				}			
					Thread connect = new Thread(getXml);
					connect.start();			
			}
		});
	}

	// lấy dữ liệu của thẻ <Step>
	private void getDataOfStepNode(NodeList nodelist) {
		size = nodelist.getLength();
		instructions = new String[size];
		for (int i = 0; i < size; i++) {
			Element node = (Element) nodelist.item(i);
			Element instructionsNode = (Element) node.getElementsByTagName(
					"html_instructions").item(0);
			instructions[i] = i + 1 + ".. "
					+ getStringOfHtmlInstructions(instructionsNode) + "\n"
					+ ". ";
		}

	}

	// xử lí xâu trong thẻ <html_instructions>
	private String getStringOfHtmlInstructions(Element iNode) {

		String str = iNode.getTextContent();

		String str1[] = str.split("<b>");
		str = printString2(str1);
		String strs2[] = str.split("</b>");
		str = printString2(strs2);
		String str3[] = str.split("<div style=\"font-size:0.9em\">");
		str = printString2(str3);
		String str4[] = str.split("</div>");
		str = printString2(str4);

		return str;

	}

	private String printString(String[] s) {
		String str = "";
		for (int i = 0; i < s.length; i++) {
			str = str + s[i] + "\n";
		}
		return str;
	}

	private String printString2(String[] s) {
		String str = "";
		for (int i = 0; i < s.length; i++) {
			str = str + s[i];
		}
		return str;
	}

	public void onInit(int status) {
		// TODO Auto-generated method stub
		if (status == TextToSpeech.SUCCESS) {
			int res = tts.setLanguage(Locale.US);
			if (res == TextToSpeech.LANG_MISSING_DATA
					|| res == TextToSpeech.LANG_NOT_SUPPORTED) {
				Toast.makeText(getApplicationContext(),
						"Language is not supported!", 1).show();

			} else {
				getAudio_Direction.setEnabled(true);

			}

		} else {
			Toast.makeText(getApplicationContext(), "error", 1).show();
		}

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub

		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			tts.stop();
		}
		return super.onTouchEvent(event);
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (tts != null) {
			tts.stop();
			tts.shutdown();
		}
	}

}
